package com.google.code.coma.gui.space;

import com.google.code.coma.domain.Order;
import com.google.code.coma.domain.Part;
import com.google.code.coma.gui.DataProvider;
import com.google.code.coma.space.SelectAllSelectorCallback;
import com.google.code.coma.space.SpaceSelector;
import javafx.application.Platform;
import javafx.scene.control.ListView;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mozartspaces.core.Entry;
import org.mozartspaces.core.MzsCoreException;
import org.mozartspaces.notifications.Notification;
import org.mozartspaces.notifications.NotificationListener;
import org.mozartspaces.notifications.NotificationManager;
import org.mozartspaces.notifications.Operation;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Dominik Strasser, dominikstr@gmail.com
 */
public class SpaceOrderDataProvider extends AbstractSpaceDataProvider<Order> {
	private static final Log log = LogFactory.getLog(SpaceOrderDataProvider.class);

	public SpaceOrderDataProvider(String spaceURI, String container) {
		super(spaceURI, container);
	}

	@Override
	public void bind(ListView<Order> orderListView) {
		orderListView.setItems(data);
		try {
			data.addAll(capi.read(containerReference, new SpaceSelector(new SelectAllSelectorCallback()), 1000, null).toArray(new Order[]{}));
		} catch (MzsCoreException e) {
			//nothing to do here
		}
		NotificationManager notifManager = new NotificationManager(core);
		try {
			notifManager.createNotification(containerReference, new NotificationListener() {
				@Override
				public void entryOperationFinished(Notification source, Operation operation, final List<? extends Serializable> entries) {
					final List<Order> newData;
					try {
						newData = capi.read(containerReference, new SpaceSelector(new SelectAllSelectorCallback()), 1000, null);
					} catch (MzsCoreException e) {
						log.warn("Unable to update list", e);
						return;
					}
					Platform.runLater(new Runnable() {
						@Override
						public void run() {
							data.clear();
							data.addAll(newData);
						}
					});
				}
			}, Operation.WRITE);
		} catch (Exception e) {
			log.error("Unable to create notification", e);
		}
	}
}
